<script lang="ts" setup>
import type { InventoryTransaction } from '../inventory/types';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getInventoryList } from '#/api/inventory/inventory';
import { $t } from '#/locales';

import { useColumns, useGridFormSchema } from './data';
import TransactionDetailModal from './modules/TransactionDetailModal.vue';

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: TransactionDetailModal,
  destroyOnClose: true,
});

/**
 * 查看事务详情
 */
function onDetail(row: InventoryTransaction) {
  detailModalApi.setData(row).open();
}

/**
 * 导出数据
 */
async function handleExport() {
  try {
    // 直接调用API进行导出
    await getInventoryList({ page_size: 1000 });
    message.success('导出成功');
  } catch (error) {
    message.error('导出失败');
  }
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<InventoryTransaction>) {
  switch (code) {
    case 'detail': {
      onDetail(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    submitOnChange: true,
  },
  gridEvents: {},
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          const queryParams = {
            ...formValues,
            page_size: page.pageSize,
            page_num: page.currentPage,
          };

          // 处理时间范围
          if (formValues.date_range && formValues.date_range.length === 2) {
            queryParams.start_date =
              formValues.date_range[0].format('YYYY-MM-DD');
            queryParams.end_date =
              formValues.date_range[1].format('YYYY-MM-DD');
          }

          // 直接调用API获取列表数据
          return await getInventoryList(queryParams);
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      zoom: true,
      search: true,
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <DetailModal @success="refreshGrid" />
    <Grid table-title="库存事务记录">
      <template #toolbar-tools>
        <Button
          type="default"
          @click="handleExport"
          v-permission="'inventory:transaction:export'"
        >
          {{ $t('ui.actionTitle.export') }}
        </Button>
      </template>
    </Grid>
  </Page>
</template>

<style scoped>
.inventory-transaction-page {
  padding: 20px;
}

.transaction-content {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}
</style>
